using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using CthulhuDomain.Services;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;

namespace CthulhuDomain.StageManagement
{
  public class GameOverStage : Stage
  {
    protected LevelStage.eLinkedInfoLoaded LinkedInfoLoaded { get; set; }
    public override sealed IColor BackgroundColor { get; set; }
    protected long CurrentScore { get; set; }

    protected IsolatedStorageFile CurrentIsolatedStorage { get; set; }
    private List<long> HighScores { get; set; }

    public GameOverStage(IGameServiceProvider gameServiceManager, long score) {
      GameServiceProvider = gameServiceManager;
      BackgroundColor = new ColorAdapter(Color.CornflowerBlue);
      HighScores = new List<long>();
      CurrentScore = score;
    }

    public override void LoadContent() {

    }

    public override StateManagerResult Update(IRectangle context, Keys[] pressedKeys, IGameTime gameTime) {
      EnsureContent();
      return new StateManagerResult(eStateManagerResult.Continue, 0, 0);
    }

    public override void Draw() {
      EnsureContent();

      for (int i = 0; i < HighScores.Count; i++) {
        GameServiceProvider.SpriteBatch.DrawString(Font, HighScores[i].ToString(CultureInfo.InvariantCulture), new Vector2Adapter(0, i * 20), new ColorAdapter(Color.Blue));
      }
    }

    public override void Initialize() {

    }

    private void EnsureContent() {
      if (Convert.ToBoolean(LinkedInfoLoaded & LevelStage.eLinkedInfoLoaded.Content)) return;
      InitHighScore();
      Font = GameServiceProvider.ContentManager.LoadFont("Impact");

      LinkedInfoLoaded |= LevelStage.eLinkedInfoLoaded.Content;
    }

    private void InitHighScore() {
      try {
        CurrentIsolatedStorage = IsolatedStorageFile.GetUserStoreForDomain();
        if (CurrentIsolatedStorage.FileExists("high_scores.txt")) {
          try {
            using (var hsf = new StreamReader(CurrentIsolatedStorage.OpenFile("high_scores.txt", FileMode.Open))) {
              var hsf_s = hsf.ReadToEnd();
              if (hsf_s != string.Empty)
              {
                var p = hsf_s.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                HighScores = (from string c in p select long.Parse(c)).ToList();
              }
            }
          }
          catch(Exception ex)
          {
            throw new Exception(ex.Message);
          }
          finally {
            HighScores.Add(CurrentScore);
            HighScores = HighScores.OrderByDescending(x => x).ToList();
            HighScores = HighScores.Take(3).ToList();
          }

          using (
            var hsf = new StreamWriter(CurrentIsolatedStorage.OpenFile("high_scores.txt", FileMode.Create))) {
            HighScores.ForEach(x => hsf.WriteLine(x.ToString(CultureInfo.InvariantCulture)));
          }
        }
      }
      catch (Exception ex) {
        throw new Exception(ex.Message);
      }
    }

  }
}